package uoc.biblioteca.struts.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import uoc.biblioteca.mappings.dao.HistoricExcelsHome;
import uoc.biblioteca.mappings.dao.MilleniumHome;
import uoc.biblioteca.mappings.dao.ProveedorHome;
import uoc.biblioteca.mappings.object.HistoricExcelsVo;
import uoc.biblioteca.mappings.object.MilleniumVo;
import uoc.biblioteca.mappings.object.ProveedorVo;
import uoc.biblioteca.mappings.object.UserVo;
import uoc.biblioteca.struts.form.GenerateExcelForm;
import uoc.biblioteca.struts.form.ReadMilleniumForm;
import uoc.biblioteca.struts.form.SendMailForm;
import uoc.biblioteca.util.GenerateExcelProveidor;
import uoc.biblioteca.util.SendMail;

public class GenerateExcelAction extends BaseAction {
    
   
	private static final Log log = LogFactory.getLog(MisSolicitudsListAction.class);
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
    
		
		GenerateExcelForm  generateExcelForm = (GenerateExcelForm ) form;
		
			try{
				
				 //Comprobar si la session esta guardada
				UserVo userLogin = obtenerUserSession(request);
				if(userLogin==null){
					request.getSession().setAttribute("ERROR","\n" +NO_USER_SESSION);
					return mapping.findForward("errorNotUser");
				}
			    
				if (("goToMenu").equals(generateExcelForm.getAction())){
			    	return goToMenu(mapping, form, request, response);
			    }
				else if (("generateExcel").equals(generateExcelForm.getAction())){
			    	return generateExcel(mapping, form, request, response);
			    }
				else if (("deleteExcel").equals(generateExcelForm.getAction())){
			    	return deleteExcel(mapping, form, request, response);
			    }
				else if (("deleteExcelByDate").equals(generateExcelForm.getAction())){
			    	return deleteExcelByDate(mapping, form, request, response);
			    }
				else{
					return goToMenu(mapping, form, request, response);
				}
			
			}
			catch (Exception e) {
				e.printStackTrace();
				log.error("Error: ", e);
				request.getSession().setAttribute("ERROR","\n" +e.toString()  );
				return mapping.findForward("error");
			}
			
	}

	
	public ActionForward goToMenu(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
		GenerateExcelForm  generateExcelForm = (GenerateExcelForm ) form;
		
		
		try{
			MilleniumHome milleniumHome = new MilleniumHome();
			
			ProveedorHome proveedorHome = new ProveedorHome();
			HistoricExcelsHome historicHome = new HistoricExcelsHome();
			
			generateExcelForm.setProveedoresCodes(milleniumHome.getAllProveedoresNewAdquisicions());
			
			generateExcelForm.setHistoricProveedores(historicHome.getAllHistoricExcels());
			
			List proovedoresList = new ArrayList<ProveedorVo>();
			
			for(int i=0;i<generateExcelForm.getProveedoresCodes().length;i++){
				String code = generateExcelForm.getProveedoresCodes()[i];
				ProveedorVo proveedor = proveedorHome.findProveedorByCode(code);
				
				if(proveedor.getIdProveedor()==null){
					proveedor.setCodeProveedor(code);
					proveedor.setNom(code);
					proveedor.setIsExport(1);
					proveedorHome.saveNew(proveedor);
					proveedor = proveedorHome.findProveedorByCode(code);
				}
				
				proovedoresList.add(proveedor);
			}
			
			generateExcelForm.setProveedores((ProveedorVo[]) proovedoresList.toArray(new ProveedorVo[0]));
			
			
			//generateExcelForm.setProveedores(proveedorHome.getAllProveedoresExportables());
			
			return mapping.findForward("menuProveidor");
		}
		catch (Exception e) {
			e.printStackTrace();
			log.error("Error: ", e);
			request.getSession().setAttribute("ERROR","\n" +e.toString()  );
			return mapping.findForward("error");
		}
	}
	
	public ActionForward generateExcel(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
		GenerateExcelForm  generateExcelForm = (GenerateExcelForm ) form;
		
		
		try{
			
			MilleniumHome milleniumHome = new MilleniumHome();
			
			MilleniumVo[] milleniumList =null;
			
			String codeProv = request.getParameter("codeProv");
			
			if(codeProv!=null && !codeProv.equals("")){
				milleniumList = milleniumHome.getNewAdquisicionsByProveedor(codeProv);
			}
			
			Calendar calendario = GregorianCalendar.getInstance();
			Date fecha = calendario.getTime();
			SimpleDateFormat formatoDeFecha = new SimpleDateFormat("yyyyMMdd");
			
			//Get the file name
			String fileName    = "C_"+formatoDeFecha.format(fecha)+"-"+codeProv+".xls";
			
			 //Get the servers upload directory real path name
	        //String filePath = getServlet().getServletContext().getRealPath("/") +"export";
	        //String filePath ="/opt/local/home_biblioteca/configHome/adquisicions/export";
	        String filePath =(String) request.getSession().getAttribute("pathExport");
	        
	        
			GenerateExcelProveidor generator = new GenerateExcelProveidor();
			generator.setFileName(fileName);
			generator.setFilePath(filePath);
			
			generator.generate(milleniumList);
			
			request.setAttribute("fileName", fileName);
			request.getSession().setAttribute("fileNameExport",fileName);
			
			
			//Desa historic
			HistoricExcelsVo historicExcels = new HistoricExcelsVo();
			HistoricExcelsHome historicHome = new HistoricExcelsHome();
			
			
			historicExcels=historicHome.findHistoricByFileName(fileName);
			
			if(historicExcels==null) {
				historicExcels = new HistoricExcelsVo();
			}
			
			historicExcels.setDateGenerate(fecha);
			historicExcels.setNameProveedor(codeProv);
			historicExcels.setFileCreate(fileName);
			
			
			ProveedorVo proveedor = new ProveedorVo();
			ProveedorHome proveedorHome = new ProveedorHome();
			proveedor = proveedorHome.findProveedorByCode(codeProv);
			historicExcels.setIdProveedor(proveedor.getIdProveedor());
			
			historicHome.saveNew(historicExcels);
			
			
			
			
			
			return goToMenu(mapping, generateExcelForm, request, response);
		}
		catch (Exception e) {
			e.printStackTrace();
			log.error("Error: ", e);
			request.getSession().setAttribute("ERROR","\n" +e.toString()  );
			return mapping.findForward("error");
		}
	}
	
	
	public ActionForward deleteExcel(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
		GenerateExcelForm  generateExcelForm = (GenerateExcelForm ) form;
		
		
		try{
			
			MilleniumHome milleniumHome = new MilleniumHome();

			//Desa historic
			HistoricExcelsVo historicExcels = new HistoricExcelsVo();
			HistoricExcelsHome historicHome = new HistoricExcelsHome();
			
			
			String idHistoric = request.getParameter("idHistoricExcels");
			
			if(idHistoric!=null && !idHistoric.equals("")){
				historicExcels = historicHome.findById(new Integer(idHistoric));
			}
			
			//Get the file name
			String fileName    = historicExcels.getFileCreate();
			
			 //Get the servers upload directory real path name
	        //String filePath = getServlet().getServletContext().getRealPath("/") +"export";
	        String filePath = (String) request.getSession().getAttribute("pathExport");
			
			File fileXls = new File(filePath,fileName);
			
			if (fileXls.delete())
				System.out.println("El fichero " + filePath+fileName + " ha sido borrado correctamente");
			else
				System.out.println("El fichero " + filePath+fileName + " no se ha podido borrar");
			
			
			request.setAttribute("fileNameDelete", fileName);
			
			historicHome.delete(historicExcels);
			
			return goToMenu(mapping, generateExcelForm, request, response);
		}
		catch (Exception e) {
			e.printStackTrace();
			log.error("Error: ", e);
			request.getSession().setAttribute("ERROR","\n" +e.toString()  );
			return mapping.findForward("error");
		}
	}
	
	public ActionForward deleteExcelByDate(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
		GenerateExcelForm  generateExcelForm = (GenerateExcelForm ) form;
		
		
		try{
			
			MilleniumHome milleniumHome = new MilleniumHome();

			//Desa historic
			HistoricExcelsVo historicExcels = new HistoricExcelsVo();
			HistoricExcelsHome historicHome = new HistoricExcelsHome();
			
			 //Get the servers upload directory real path name
	        //String filePath = getServlet().getServletContext().getRealPath("/") +"export";
	        //String filePath ="/opt/local/home_biblioteca/biblioteca/data/adquisicions/export";
	        String filePath =(String) request.getSession().getAttribute("pathExport");
	        
	        
			HistoricExcelsVo[] historicExcelList = historicHome.findHistoricExcelsLast();
			
			if(historicExcelList!=null && historicExcelList.length>0){
				
				for(int i=0;i<historicExcelList.length;i++){
					historicExcels = historicExcelList[i];
					
					//Get the file name
					String fileName    = historicExcels.getFileCreate();
					
				    File fileXls = new File(filePath,fileName);
					
					if (fileXls.delete())
						System.out.println("El fichero " + filePath+fileName + " ha sido borrado correctamente");
					else
						System.out.println("El fichero " + filePath+fileName + " no se ha podido borrar");
					
					request.setAttribute("fileNameDelete", fileName);
					
					historicHome.delete(historicExcels);
					
				}
				
			}
			
			return goToMenu(mapping, generateExcelForm, request, response);
		}
		catch (Exception e) {
			e.printStackTrace();
			log.error("Error: ", e);
			request.getSession().setAttribute("ERROR","\n" +e.toString()  );
			return mapping.findForward("error");
		}
	}
	
	
	public ActionForward listNewAdquisicions(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
		GenerateExcelForm  generateExcelForm = (GenerateExcelForm ) form;
		
		
		try{
		
			MilleniumHome milleniumHome = new MilleniumHome();
			
			generateExcelForm.setStructure(milleniumHome.getAllNewAdquisicions());
			
			generateExcelForm.setProveedoresCodes(milleniumHome.getAllProveedoresNewAdquisicions());
			
			
			
			return mapping.findForward("readListMillenium");
		}
		catch (Exception e) {
			e.printStackTrace();
			log.error("Error: ", e);
			request.getSession().setAttribute("ERROR","\n" +e.toString()  );
			return mapping.findForward("error");
		}
	
	}
	
}